package handlers

import (
	"cargo-master/cache"
	"cargo-master/models"
	"cargo-master/pgk"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if password == "" || username == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户名密码不能为空",
		})
		return
	}
	rdeis_key := "login_" + username
	CountData, _ := cache.Rdb.Get(cache.Ctx, rdeis_key).Int()
	if CountData >= 3 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误三次禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pgk.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, rdeis_key)
		if CountData == 2 {
			cache.Rdb.Set(cache.Ctx, rdeis_key, 3, time.Hour*2)
		}
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	roleNode := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&roleNode)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色权限分配成功",
	})
	return
}
func UserRole(c *gin.Context) {
	var role []models.Role
	uid := c.Query("uid")
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid=?", uid).Debug().Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}
func RoleNode(c *gin.Context) {
	var node []models.Node
	rid := c.Query("rid")
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes on role_nodes.nid=nodes.id").
		Where("role_nodes.rid=?", rid).Debug().Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}
